/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    CCell, Cell, Table, TableBody, TableRow, Text, TableHead,
} from "customize-easy-ui-component";
import {DirectLink, Link as RouterLink} from "../../../routing/Link";
import {useFoldForList, useFoldGenerate, useSplitSubCapacity,} from "../../hook/useMainRepUrlOr";
import {Each_ZdSetting, tabIBlistCb, useTableEditor} from "../../hook/useRepTableEditor";
import {InspectRecordLayout, InternalItemProps, useItemInputControl} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {TailMenRowIspCheck} from "../../contain/rarelyVary";

const 级别选=['GC2', ];
const 敷设选=['架空', ];
const config单元表=[
  ['名称','name',90],['管道编号','code',90],['级别','level',70,tabIBlistCb(级别选,1)],['材质','材料',150,undefined,'svp'],
  ['介质','工介',120,undefined,'pa'], ['外径(mm)','dia',80],['壁厚(mm)','thik',85], ['长度(m)','leng',70],['起点','start',100],['终点','stop',100],
  ['设计温度','设温',75,undefined,'svp'],['设计压力','设压',75,undefined,'svp'], ['工作温度','工温',75,undefined,'pa'],['工作压力','工压',75,undefined,'pa'],
  ['敷设','lay',60,tabIBlistCb(敷设选,1)],['图号','图号',190,undefined,'pa'],['说明','mm',130,]
] as Each_ZdSetting[];

const itemA单元表=['单元表',];
/**特性表的构建: 因为是制造监验的业务，所以没有关联管道单元的台账；就只能手动录入，不能从像普通业务那样从单元的台账选。ManufactCharacter
 * */
export const ManufactCharacter =
  React.forwardRef((
      {children, show, alone = true, refWidth, label, }: InternalItemProps, ref
  ) => {
      const [getInpFilter]=useMeasureInpFilter(null,itemA单元表,);
      const {inp, setInp} = useItemInputControl({ ref });
      const headview=<><Text>
          说明：其中的中间4个组合的二级字段关系如下示意。
      </Text>
      <Table css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
          <TableBody>
              <TableRow>
                  <CCell colSpan={3}>管道规格</CCell><CCell colSpan={2}>起止点</CCell><CCell colSpan={2}>设计条件</CCell><CCell colSpan={2}>工作条件</CCell>
              </TableRow>
              <TableRow>
                  <CCell>公称外径(mm)</CCell><CCell>公称壁厚(mm)</CCell><CCell>管道长度(m)</CCell><CCell>起点</CCell><CCell>终点</CCell>
                  <CCell>温度（℃）</CCell><CCell>压力（MPa）</CCell><CCell>温度（℃）</CCell><CCell>压力（MPa）</CCell>
              </TableRow>
          </TableBody>
      </Table>
      注：底下编辑部分抬头简化了字段名。<br/>
      </>;
      const [render]=useTableEditor({inp,setInp,
                          headview, config: config单元表, table:'单元表', maxRf:2});
      return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            {render}
            {children}
          </InspectRecordLayout>
      );
});

//实际表5列 和才2列的：宽度可自己调节
const CLnPercents=[['12%',"%","55%"], ['9%',"%","37%","37%"],
                 ['7%',"%","25%","25%","25%"], ['6%',"%","20%","20%","20%","20%"]];
//export const CharacteristRow= ({title, dlPage, rep,where,field,span,pref} : {title:string, dlPage: any,rep: any,where?:number,field:string,span?:number,pref?:string}
//pref=null
const CharacteristRow= (title:string,dlPage: any,field:string,rep: any,where?:number, pref?:string|null, span?:number
) => {
  return <TableRow >
    { pref? <><CCell rowSpan={span}>{pref}</CCell><CCell>{title}</CCell></>
        : pref===null? <CCell>{title}</CCell>
            : <CCell colSpan={2}>{title}</CCell>
    }
    { dlPage.map((p: any, c:number) =>
        <DirectLink key={c} href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/ManufactCharacter?ppcode=`+p?.code+'#ManufactCharacter'}>
          <CCell key={c}>{
            where===1? p?.svp?.[field] :
                where===2? p?.pa?.[field] :
                    p?.[field]}</CCell>
        </DirectLink>
    ) }
  </TableRow>;
};
/**【特别布局】打印 版面很是宽松的：单独占用一页A4纸张的， 内容居中的。 但前提：内容必定少于一页的！
 * */
export const ManufactCharacterVw= ({ orc, rep, children } : { orc: any,rep: any,children?: React.ReactNode;}
) => {
  //重组成二维 orc?.单元表?.=> 四个一页的组合。pages[ [1{单元},2,3,undefined ] , ]
  const pages= React.useMemo( () => {
    let pages: any[]=[];
    for(let f=0; f<orc?.单元表?.length; f+=4){
        pages.push( orc?.单元表?.slice(f,f+4) );
    }
    return pages;
  }, [orc?.单元表]);

  const lsBlockMax=useSplitSubCapacity(pages.length,4);
  const {sumArea, areaContent, btnBindUses}=useFoldForList(pages, lsBlockMax,false);
  const frCallback = (dlPage: any, arak:number, pid:number) => {
    const pn=arak * lsBlockMax;     //特性表第几张的 基数
    const xsize=dlPage.length;
    let 检验员s: any[]=[];
    for (const pp of dlPage) {
      if(pp?.sgm){
        const men =检验员s.find((m: any) => m.name === pp?.sgm.name);
        if(!men)  检验员s.push(pp?.sgm);
      }
    }
    return <div key={pid} css={{display: 'flex',flexDirection: 'column',justifyContent: 'space-between',
                "@media print": {pageBreakInside: 'avoid', height: '100vh'},
         }}>
              <DirectLink  href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/ManufactCharacter#ManufactCharacter`}>
                <Text  variant="h2" css={{textAlign: 'center', marginTop: '1rem',
                  "@media print": {
                    pageBreakBefore: 'always', marginTop: 'unset',
                  },
                }}
                >压力管道数据表</Text>
              </DirectLink>
            <div>
              <div css={{display: 'flex', justifyContent: 'flex-end',}}>
                <Text>证书编号：{rep.isp.no}</Text>
              </div>
              <Table fixed={ CLnPercents[xsize-1]  } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
                <TableHead>
                  <TableRow>
                    <CCell colSpan={2}>序号</CCell>
                    { dlPage.map((p: any, c:number) =>
                        <CCell key={c}><Text  id={`Characteristics${(pn+pid)*4 + c}`}>{ (pn+pid)*4 + c+1 }</Text></CCell>
                    ) }
                  </TableRow>
                </TableHead>
                <TableBody>
                  {CharacteristRow('管道名称',dlPage,'name',rep, )}
                  {CharacteristRow('管道编号',dlPage,'code',rep, )}
                  {CharacteristRow('管道级别',dlPage,'level',rep, )}
                  {CharacteristRow('材质',dlPage,'材料',rep, 1)}
                  {CharacteristRow('介质',dlPage,'工介',rep, 2)}
                  {CharacteristRow('公称外径 (mm)',dlPage,'dia',rep, 0,'管道规格',3)}
                  {CharacteristRow('公称壁厚 (mm)',dlPage,'thik',rep, 0,null)}
                  {CharacteristRow('管道长度(m)',dlPage,'leng',rep, 0,null)}
                  {CharacteristRow('起点',dlPage,'start',rep, 0,'起止点',2)}
                  {CharacteristRow('终点',dlPage,'stop',rep, 0,null)}
                  {CharacteristRow('温度（℃）',dlPage,'设温',rep, 1,'设计条件',2)}
                  {CharacteristRow('压力（MPa）',dlPage,'设压',rep, 1,null)}
                  {CharacteristRow('温度（℃）',dlPage,'工温',rep, 2,'工作条件',2)}
                  {CharacteristRow('压力（MPa）',dlPage,'工压',rep, 2,null)}
                  {CharacteristRow('敷设方式',dlPage,'lay',rep, )}
                  {CharacteristRow('备注（图号）',dlPage,'图号',rep,2 )}
                    <TableRow>
                        {/*这里备注实际是4个管道单元需分别做录入的。 然后这里合并显示*/}
                        <Cell colSpan={xsize + 2}>
                            说明：&nbsp;
                            { dlPage.map((p: any, c:number) => p?.mm && <React.Fragment key={c}>
                                &nbsp;{p?.mm}。
                            </React.Fragment> )
                            }
                        </Cell>
                    </TableRow>
                </TableBody>
              </Table>
            </div>
         <TailMenRowIspCheck orc={orc} rep={rep} />
    </div>
  };
  const [renderAll]=useFoldGenerate({sumArea,btnBindUses,areaContent, callback:frCallback,mark:'特性表折叠'});
  return <>
    { pages.length<=0 && <RouterLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/ManufactCharacter#ManufactCharacter`}>
            <Text variant="h2" css={{textAlign: 'center', marginTop: '1rem',
                 "@media print": {display: 'none',},
            }}>管道数据表的单元录入</Text>
          </RouterLink>
    }
    <div id="ManufactCharacter"></div>
    { renderAll }
    { children }
  </>;
};
